package com.zhentao.tools;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhentao.pojo.Product;
import com.zhentao.service.CustomerServiceTransferService;
import com.zhentao.service.ProductService;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class MyTools {

    @Autowired
    private ProductService productService;

    @Autowired
    private CustomerServiceTransferService customerServiceTransferService;

    // 当前会话信息（通过ThreadLocal或其他方式传递）
    private static final ThreadLocal<Integer> currentUserId = new ThreadLocal<>();
    private static final ThreadLocal<String> currentConversationId = new ThreadLocal<>();

    /**
     * 设置当前会话上下文
     */
    public static void setCurrentContext(Integer userId, String conversationId) {
        currentUserId.set(userId);
        currentConversationId.set(conversationId);
    }

    /**
     * 清除当前会话上下文
     */
    public static void clearCurrentContext() {
        currentUserId.remove();
        currentConversationId.remove();
    }

    // 转人工服务
    @Tool(description = "当用户询问转人工、人工客服、联系客服、投诉建议等相关问题时，调用此工具进行真实的转人工服务")
    public String transfer(String question) {
        System.out.println("调用转人工Tools工具，用户问题: " + question);

        try {
            // 检查是否为转人工请求
            if (!customerServiceTransferService.isTransferRequest(question)) {
                return null;
            }

            // 获取当前会话上下文
            Integer userId = currentUserId.get();
            String conversationId = currentConversationId.get();

            System.out.println("转人工请求 - 用户ID: " + userId + ", 会话ID: " + conversationId);

            // 处理转人工请求
            Map<String, Object> transferResult = customerServiceTransferService.handleTransferToHuman(
                userId, conversationId, question
            );

            if (transferResult.get("success").equals(true)) {
                return (String) transferResult.get("message");
            } else {
                return (String) transferResult.get("message");
            }

        } catch (Exception e) {
            System.err.println("转人工工具调用失败: " + e.getMessage());
            e.printStackTrace();
            return "转人工服务暂时不可用，请稍后再试。如有紧急问题，请拨打客服热线：15993867352";
        }
    }

    @Tool(description = "根据商品名称获取商品")
    public String getProductList(String name) {
        System.out.println("调用商品列表Tools工具，商品名称: " + name);
        QueryWrapper<Product> wrapper = new QueryWrapper<>();
        wrapper.like(name != null, "name", name);
        return productService.list(wrapper).toString();
    }





}
